package br.org.etec.dotcao.mailer;

import java.util.Set;
import java.util.concurrent.Callable;

import org.apache.log4j.Logger;

public class MailerTask implements Callable<Long> {

	private Sender sender;
	private Set<Receiver> receivers;
	private String subject;
	private String fileContent;
	private String charset;
	private Receiver replyTo;
	
	private Logger successLogger;
	private Logger errorLogger;

	public MailerTask(Sender sender, Set<Receiver> receivers, String subject,
			String fileContent, String charset, Receiver replyTo) {
		super();
		this.sender = sender;
		this.receivers = receivers;
		this.subject = subject;
		this.fileContent = fileContent;
		this.charset = charset == null || charset.isEmpty() ? "utf-8" : charset;
		this.replyTo = replyTo;
		
		try {
			successLogger = LogBuilder.successLogger(getClass());
			errorLogger = LogBuilder.errorLogger(getClass());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Long call() throws Exception {
		long success = 0;
		
		for (Receiver receiver : receivers) {
			Mailer mailer = new Mailer();
			mailer.addReceiver(receiver);
			mailer.setSender(sender);
			mailer.setCharset(charset);
			mailer.setFileContent(fileContent);
			mailer.setReplyTo(replyTo);
			mailer.setSubject(subject);
			
			try {
				mailer.send();
				success++;
				System.out.println("E-mail enviado com sucesso para: " + receiver.getEmail());
				successLogger.info("E-mail enviado com sucesso para: " + receiver.getEmail());
				
			} catch (Exception e) {
				errorLogger.error("Erro enviando e-mail para: " + receiver.getEmail(), e);
			}
		}
		
		return success;
	}

}
